package tags;

import dao.DAOFactory;
import dao.ICountryDAO;
import dao.tro.Country;
import dao.tro.CountryNameAsc;

import javax.servlet.ServletException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class MainCountryTag extends TagSupport {
    private int countryCount;

    public int getCountryCount() {
        return countryCount;
    }

    public void setCountryCount(int countryCount) {
        this.countryCount = countryCount;
    }

    @Override
    public int doStartTag() throws JspException {
        return EVAL_BODY_INCLUDE;
    }

    @Override
    public int doEndTag() throws JspException {
        ArrayList<Country> countryList = (ArrayList<Country>) DAOFactory.getDAOFactory(1).getCountryDAO().countryList(countryCount);
        Collections.sort(countryList, new CountryNameAsc());
        for (Country country: countryList) {
            try {
                pageContext.setAttribute("singleCountry", country, PageContext.REQUEST_SCOPE);
                pageContext.include("../Templates/Country.jsp");
            } catch (ServletException | IOException e) {
                throw new JspException();
            }
        }
        return EVAL_PAGE;
    }
}
